package bth.reconfs;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;

/* Requete HTTP depuis internet */ // Against ERROR with API > 9 NetworkOnMainThreadException
public class HttpRequestTask extends AsyncTask<List<Object>, Void, String>
{	
	protected String doInBackground(List<Object>... params) {
		ArrayList<String> requestParameters = new ArrayList<String>();
		ArrayList<NameValuePair> sentParameters = new ArrayList<NameValuePair>();
		String result = "";	// String generally JSON
		for (Object obj : params[0]) {
			//Log.d("obj.hashCode()", ""+obj.hashCode());
			if( obj.hashCode()==571365569 || obj.hashCode()==568974167 )
			{
				requestParameters = (ArrayList<String>) obj;
			}
			else
			{
				sentParameters = (ArrayList<NameValuePair>) obj;
			}
		}
		//Log.d("params",requestParameters.toString()+"\n"+sentParameters.toString());

		// Get httpClient object
		HttpClient httpclient = new DefaultHttpClient();
		try {
			if( requestParameters.get(1).toString().equals("GET") )	// Create and launch the GET request
			{
				HttpGet httpRequest = new HttpGet(requestParameters.get(0).toString()+"?"+URLEncodedUtils.format(sentParameters, "utf-8"));
				BasicResponseHandler responseHandler = new BasicResponseHandler();
				result = httpclient.execute(httpRequest, responseHandler);// Decode received data

			} else {	// Create and launch the POST request
				HttpPost httpRequest = new HttpPost(requestParameters.get(0).toString());// Link to the target website
				httpRequest.setEntity(new UrlEncodedFormEntity(sentParameters));	// addParameters
				HttpResponse response = httpclient.execute(httpRequest);			// Launch the request
				result = EntityUtils.toString(response.getEntity());	// Decode received data
			}
		} catch (Exception e) {
			Log.e("HttpRequestTask()", e.toString());
		}
		return result;
	}
}